import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
        username: localStorage.getItem('username') ? localStorage.getItem('username') : '',
        nickname: localStorage.getItem('nickname') ? localStorage.getItem('nickname') : '',
        picture: localStorage.getItem('picture') ? localStorage.getItem('picture') : '',
        permissions: localStorage.getItem('permissions') ? localStorage.getItem('permissions') : '',
        regday: localStorage.getItem('regday') ? localStorage.getItem('regday') : ''
    },
    mutations: {
        setToken(state, token) {
            state.token = token; // 直接赋值 token
            localStorage.setItem("token", token); // 存储 token 字符串
        },
        setUser(state, user) {
            if (user) {
                state.username = user.username;
                state.nickname = user.nickname;
                state.picture = user.picture;
                state.permissions = user.permissions;
                state.regday = user.regday;
                localStorage.setItem("username", user.username);
                localStorage.setItem("nickname", user.nickname);
                localStorage.setItem("picture", user.picture);
                localStorage.setItem("permissions", user.permissions);
                localStorage.setItem("regday", user.regday);
            } else {
                console.error("用户信息不存在");
            }
        },
        setUsername(state, username) {
            console.log("设置用户名:", username);
            state.username = username; // 直接赋值 username 字符串
            localStorage.setItem("username", username); // 同时存储到 localStorage
        },
        setPermissions(state, permissions) {
            state.permissions = permissions
            localStorage.setItem("permissions", permissions)
        },
        setNickname(state, nickname) {
            state.nickname = nickname;
            localStorage.setItem("nickname", nickname);
        },
        setPicture(state, picture) {
            state.picture = picture;
            localStorage.setItem("picture", picture);
        },
        delToken(state) {
            state.token = '';
            state.username = '';
            state.nickname = '';
            state.picture = '';
            state.permissions = '';
            state.regday = '';
            localStorage.clear();
        }
    }
})

export default store;